# -*- coding: utf-8 -*-
'''
Created on 2012-8-22

@author: xiaolei
'''
from flask import g, Blueprint, render_template, redirect, url_for, session, current_app, jsonify
from flask.globals import request
from services import UserService
from models import User
from datetime import timedelta
from flaskext.babel import gettext

user_view = Blueprint("user", __name__);

@user_view.route("/")
def index():
    return render_template("user/sign_in.html");

def _write_user_session(user):
    g.user = user;
    if user != None:
        session.permanent = False; 
        session["userid"] = user.id;
        session["username"] = user.display_name;
        session["password"] = user.password;
        session["email"] = user.email;
        session["signed_in"] = True;
    else:
        session.permanent = False;
        session.pop("userid", None);
        session.pop("username", None);
        session.pop("email", None)
        session.pop("password", None);
        session.pop("signed_in", None);

@user_view.route("/sign_in", methods=['POST', 'GET'])
def sign_in():
    if request.method == "POST":
        password = request.form["password"];
        email = request.form["email"]; 
        auto_sign_in = request.form.get("auto_sign_in", None);
        
        userService = UserService();
        user = userService.get_user(email);
        if user != None:
            if userService.check_auth(email, password):
                _write_user_session(user);
                
                # Auto sign in
                if auto_sign_in == "true":
                    session.permanent = True;
                    days = current_app.config.get("MAX_AUTO_SIGN_IN_DAYS", 2);
                    current_app.permanent_session_lifetime = timedelta(days=days);
                    current_app.logger.debug("Session timeout: " + str(current_app.permanent_session_lifetime));
                else:
                    session.permanent = False;

                """
                # next_url is a hidden field of the form. It's used to redirect to the next URL from sign in page.
                next_url = request.form.get("next_url", None);
                if next_url: 
                    return redirect(next_url);
                else:
                    return redirect(url_for("main.home", name=user.display_name));
                """
                return jsonify({"status": "OK"});
            else:
                result = {"status": "FAIL", "message": gettext(u"Incorrect email or password.")};
                return jsonify(result);
        else:
            result = {"status": "FAIL", "message": gettext(u"User does not registered.")};
            return jsonify(result);
    else:
        return render_template("user/sign_in.html", title="Sign in");  

@user_view.route("/sign_out", methods=['POST', 'GET'])
def sign_out():
    _write_user_session(None);
    
    return redirect(url_for("main.home"));

@user_view.route("/sign_up", methods=['POST', 'GET'])
def sign_up():
    error = None;
    new_id = None;
    
    if request.method == "POST":
        current_app.logger.debug(str(request.form));
        
        username = request.form.get("username", None);
        password = request.form.get("password", None);
        email = request.form.get("email", None);
      
        new_user = User();
        new_user.display_name = username;
        new_user.password = password;
        new_user.email = email;
        new_user.is_active = 1;
        
        userService = UserService();
        try:
            new_id = userService.add_user(new_user);
        except Exception as ex:
            error = gettext(u"Failed to sign up, please try again.");
            if ex and current_app.config["DEBUG"]:
                error = error + "\n" + str(ex);
            
        if new_id != None:
            user = userService.get_user(email);
            if user:
                _write_user_session(user);
                
            return redirect(url_for("main.home"));
        else:
            return render_template("user/sign_up.html", error=error);
      
    return render_template("user/sign_up.html");

@user_view.route("/edit/<email>")
def edit(email):
    return render_template("/user/user.html", email=email);
    
